<?php
include_once '../../config.php';
include_once '../../lib/database.php';
include_once '../../functions.php';


if(isset($_GET['add'])){
	$title = "Add New Author";
	$action = "addform";
	$name = '';
	$email = '';
	$button = 'Add User';
	include 'form.html';
	exit();
}

if(isset($_GET['addform'])){

	$name = $_POST['name'];
	$email = $_POST['email'];
	$sql = "INSERT INTO author SET name='$name',email='$email'";
	$insert = $db->query($sql);
	if(!$insert){
		mysql_error();
	}
	redirect('admin/authors');
	exit();
}

if(isset($_GET['action']) && $_GET['action'] == 'Delete'){

	$id = $_GET['id'];
	$sql = "SELECT id FROM joke WHERE authorid='$id'";
	
	while($row = $db->query($sql)->fetch_array()){
		$jokeid = $row[0];
		$sql = "DELETE FROM jokecategory WHERE jokeid = '$jokeid'";
		$del = $db->query($sql);
		if(!$del){
			die("error " . mysql_error());
		}
	}
/*
	$result = mysql_query($sql);
	
	while($row = mysql_fetch_array($result)){
		$jokeid = $row[0];
		$sql = "DELETE FROM jokecategory WHERE jokeid='$jokeid'";
		$del = $db->query($sql);
		if(!$del){
			die("error " . mysql_error());
		}
	}
*/
	$sql = "DELETE FROM joke WHERE authorid='$id'";
	$del = $db->query($sql);
	if(!$del){
		echo "cannot delete";
	}
	$sql = "DELETE FROM author WHERE id = '$id'";
	$del = $db->query($sql);
	if(!$del){
		echo "cannot delete";
	}
	
	redirect('admin/authors');
	exit();
}

if(isset($_GET['action']) && $_GET['action'] == 'Update'){
	$id = $_GET['id'];
	$action = 'update';
	$title = 'Edit Author';
	$button = 'Update';
	$sql = "SELECT id, name, email FROM author WHERE id='$id'";
	$row = $db->query($sql)->fetch_array();
	$name = $row['name'];
	$email = $row['email'];
	include 'form.html';
	exit();
}

if(isset($_GET['update'])){
	$id = $_POST['id'];
	$name = $_POST['name'];
	$email = $_POST['email'];
	$sql = "UPDATE author SET name='$name', email='$email' WHERE id='$id'";
	$update = $db->query($sql);
	if(!$update){
		mysql_error();
	}
	redirect('admin/authors');
	exit();

}


$sql = 'SElECT id,name, email FROM author ORDER BY id';
$result_set = $db->query($sql)->fetch_assoc();

if(!$result_set){
	die("Error with query. " . mysql_error());
}

include 'authors.php';
